import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/9 14:24
 * @description:
 */
public class Solution402 {
    public String removeKdigits(String num, int k) {
        Set<Integer> removeSet = new HashSet<>();
        Stack<Integer> stack = new Stack<>();
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < num.length(); i++) {
            int temp = num.charAt(i) - '0';
            if (stack.isEmpty() || (num.charAt(stack.peek()) - '0') <= temp) {
                stack.push(i);
            } else {
                while (!stack.isEmpty() && num.charAt(stack.peek()) - '0' > temp && k != 0) {
                    int index = stack.pop();
                    removeSet.add(index);
                    k--;
                }
                stack.push(i);
            }
        }
        for (int i = 0; i < num.length(); i++) {
            if (!removeSet.contains(i)) {
                res.append(num.charAt(i));
            }
        }
        String finalRes = res.substring(0, res.length() - k);
        return removeZeros(finalRes);
    }

    public String removeZeros(String s) {
        StringBuilder res = new StringBuilder(s);
        while (res.length() > 0 && res.charAt(0) == '0') {
            res.deleteCharAt(0);
        }
        if (res.length() == 0) {
            return "0";
        } else {
            return res.toString();
        }
    }

    public static void main(String[] args) {
        Solution402 solution = new Solution402();
        System.out.println(solution.removeKdigits("1432219", 3));
        System.out.println(solution.removeKdigits("10200", 1));
        System.out.println(solution.removeKdigits("10", 2));
        System.out.println(solution.removeKdigits("10", 1));
    }
}
